#include <stdio.h>
#include "webglk.h"

extern char *romname;

glui32 glk_image_draw(winid_t win,glui32 image,glsi32 val1,glsi32 val2)
{
	glui32 t=glk_window_get_type(win);
	if (t==wintype_TextBuffer || t==wintype_Graphics)
	{
		printf("{m:'image',i:%u,p:%u,x:%d,y:%d},\n",win,image,val1,val2);
		return 1;
	}
	// no way are we going to attempt to put an image in a textgrid.
	return 0;
}
glui32 glk_image_draw_scaled(winid_t win,glui32 image,glsi32 val1,glsi32 val2,glui32 width,glui32 height)
{
	glui32 t=glk_window_get_type(win);
	if (t==wintype_TextBuffer || t==wintype_Graphics)
	{
		printf("{m:'image',i:%u,p:%u,x:%d,y:%d,w:%u,h:%u},\n",win,image,val1,val2,width,height);
		return 1;
	}
	// no way are we going to attempt to put an image in a textgrid.
	return 0;
}
#define r32(x) ((buf[x]<<24)|(buf[x+1]<<16)|(buf[x+2]<<8)|buf[x+3])
glui32 glk_image_get_info(glui32 image,glui32 *width,glui32 *height)
{
	unsigned char buf[12];
	glui32 block,numres,i;
	FILE *f;

	f=fopen(romname,"rb");
	fread(buf,4,1,f);
	if (r32(0)==0x464f524d) // FORM
	{
		fseek(f,12+8,SEEK_SET); // no need to error check here
		fread(buf,4,1,f);
		numres=r32(0);
		for (i=0;i<numres;i++)
		{
			fread(buf,12,1,f);
			if (r32(0)==0x50696374 && r32(4)==image) //Pict
			{
				fseek(f,r32(8),SEEK_SET);
				break;
			}
		}
		fread(buf,8,1,f);
		if (r32(0)==0x4a504547) //JPEG
		{
			fseek(f,4,SEEK_CUR);
			fread(buf,2,1,f);
			block=((buf[0]<<8)|buf[1])-2;
			do
			{
				fseek(f,block,SEEK_CUR);
				if (feof(f)) break;
				fread(buf,9,1,f);
				if (buf[0]!=0xff) break;
				if (buf[1]==0xc0)
				{
					*height=(buf[5]<<8)|buf[6];
					*width=(buf[7]<<8)|buf[8];
					fclose(f);
					return 1;
				}
				else block=((buf[2]<<8)|buf[3])-7;
			} while (1);
		}
		else if (r32(0)==0x504e4720) //PNG
		{
			fseek(f,8,SEEK_CUR);
			do {
				if (feof(f)) break;
				fread(buf,8,1,f);
				block=r32(0);
				if (r32(4)==0x49484452)
				{
					fread(buf,8,1,f);
					*width=r32(0);
					*height=r32(4);
					fclose(f);
					return 1;
				}
				else fseek(f,block,SEEK_CUR);
			} while (1);
		}
	}
	fclose(f);
	return 0;
}
